/*
 * Copyright (C) 2009 CityLights Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.schizoidman.android.citylights;

import java.util.Iterator;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * A BroadcastReceiver that listens for updates for the MonitorWidgetProvider.  This
 * BroadcastReceiver starts off disabled, and we only enable it when there is a widget
 * instance created, in order to only receive notifications when we need them.
 */
public class MonitorWidgetBroadcastReceiver extends BroadcastReceiver {

	/**
	 * Engages Alarm Service for this broadcast
	 * @param context
	 */
	public static void engageAlarmService(final Context context) {
		Intent intent = new Intent(context, MonitorWidgetBroadcastReceiver.class);
		PendingIntent p = PendingIntent.getBroadcast(context, 0, intent, 0);
		
		// Winding up alarm service
		AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		String sPeriod = PreferenceManager.getDefaultSharedPreferences(context).getString("polling_period", "1800000");
		long period = Long.parseLong(sPeriod);
		alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 15000, period, p);
		Log.d("CityLights", "AlarmService started with the period of " + period + "millis for the " + context);
	}
	
	/**
	 * Cancels Alarm Service for this broadcast
	 * @param context
	 */
	public static void cancelAlarmService(Context context) {
		Intent intent = new Intent(context, MonitorWidgetBroadcastReceiver.class);
		PendingIntent p = PendingIntent.getBroadcast(context, 0, intent, 0);
		AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarm.cancel(p);
		Log.d("CityLights", "AlarmService cancelled for the " + context);
	}
	
    public void onReceive(Context context, Intent intent) {
        Log.d("CityLights", "MonitorWidgetBroadcastReceiver.onReceive(" + intent + ")");
        
        Iterator<Intent> widgets = WidgetRegistry.getRegistry(context).widgetIterator();
        if (!widgets.hasNext()) {
            // No more active widgets it seems - Shutting down alarm service
        	cancelAlarmService(context);
        }

        while (widgets.hasNext()) {
        	Intent data = widgets.next();
        	data.setClass(context, ProjectWidgetUpdateService.class);
            context.startService(data);
        }
    }

}
